import FileSaver from "file-saver";
import XLSX from "xlsx";

// ============================================
// =============这里定义全局函数和变量=============
// ============================================

// 格式化URL
function formatUrl(url) {
    let env = window.localStorage.getItem("env");
    if (env == "开发环境") {
        return "/dev" + url;
    } else if (env == "测试环境") {
        return "/test" + url;
    } else {
        return "/prod" + url;
    }
}

// 格式化时间戳
function timestampFormat(cellValue) {
    if (!cellValue) {
        return "";
    }
    let timestamp = cellValue;
    if (typeof timestamp === 'string') {
        timestamp = Number(timestamp);
    }
    if (typeof timestamp !== 'number') {
        alert("输入参数无法识别为时间戳");
        return;
    }
    let value = timestamp * 1000;
    let date = new Date(value);
    let y = date.getFullYear(),
        m = date.getMonth() + 1,
        d = date.getDate(),
        h = date.getHours(),
        i = date.getMinutes(),
        s = date.getSeconds();
    if (m < 10) {
        m = '0' + m;
    }
    if (d < 10) {
        d = '0' + d;
    }
    if (h < 10) {
        h = '0' + h;
    }
    if (i < 10) {
        i = '0' + i;
    }
    if (s < 10) {
        s = '0' + s;
    }
    let t = y + '-' + m + '-' + d + ' ' + h + ':' + i + ':' + s;
    return t;
}

// JSON格式化
function jsonFormat(jsonStr) {
    return JSON.stringify(JSON.parse(jsonStr), null, "\t")
}

// JSON语法高亮
function jsonSyntaxHighlight(json) {
    if (typeof json != 'string') {
        json = JSON.stringify(json, undefined, 2);
    }
    json = json.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
    return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) {
        let cls = 'number';
        if (/^"/.test(match)) {
            if (/:$/.test(match)) {
                cls = 'key';
            } else {
                cls = 'string';
            }
        } else if (/true|false/.test(match)) {
            cls = 'boolean';
        } else if (/null/.test(match)) {
            cls = 'null';
        }
        return '<span class="' + cls + '">' + match + '</span>';
    });
}

// 导出Excel
function exportExcel(id, title) {
    /* generate workbook object from table */
    // 因为element-ui的表格的fixed属性导致多出一个table，会下载重复内容，这里删除掉
    // 判断要导出的节点中是否有fixed的表格，如果有，转换excel时先将该dom移除，然后append回去
    let fix = document.querySelector(id + '>.el-table__fixed');
    if (!fix) {
        fix = document.querySelector(id + '>.el-table__fixed-right');
        if (!fix) {
            fix = document.querySelector(id + '>.el-table__fixed-center');
        }
    }
    let wb;
    if (fix) {
        document.querySelector(id).removeChild(fix)
        wb = XLSX.utils.table_to_book(document.querySelector(id));
        document.querySelector(id).appendChild(fix);
    } else {
        wb = XLSX.utils.table_to_book(document.querySelector(id));
    }
    /* get binary string as output */
    const wbout = XLSX.write(wb, {
        bookType: 'xlsx',
        bookSST: true,
        type: 'array'
    });
    try {
        FileSaver.saveAs(
            new Blob([wbout], {
                type: 'application/octet-stream'
            }),
            title
        );
    } catch (e) {
        if (typeof console !== 'undefined') console.log(e, wbout);
    }
    return wbout;
}

// 判断图片大小和尺寸
function isImage(file, _this) {
    if (!file) {
        _this.$message({
            type: 'error',
            message: '请先上传图片'
        });
        return false;
    }
    const isImage =
        file.type === "image/png" ||
        file.type === "image/jpg" ||
        file.type === "image/jpeg";
    const isLt5M = file.size < 1024 * 1024 * 5;
    if (!isImage) {
        _this.$message.error("上传只能是png,jpg,jpeg格式!");
        return false;
    }
    if (!isLt5M) {
        _this.$message.error("上传图片大小不能超过 5MB!");
        return false;
    }
    return true;
}

// 判断是否为本地环境
function isLocalhost() {
    let host = window.location.host;
    if (host.indexOf('localhost') > -1) {
        return true;
    }
    if (host.indexOf('192.168') > -1) {
        return true;
    }
    return false;
}

// 转数组
function toArray(str) {
    let arr = [];
    arr.push(str);
    return arr;
}

// 一维数组转二维数组
function convertArray(arr, colSize) {
    let rowsData = [];
    if (!arr) {
        return rowsData;
    }
    if (arr.length === 0) {
        return rowsData;
    }
    let rowsSize = Math.ceil(arr.length / colSize);
    for (let i = 0; i < rowsSize; i++) {
        const temp = [];
        for (let j = i * colSize; j < arr.length; j++) {
            if (j < (i + 1) * colSize) {
                temp.push(arr[j]);
            } else {
                break;
            }
        }
        rowsData.push({
            cols: temp
        })
    }
    return rowsData;
}

// 格式化日期，YYYY-MM-DD
function getFormatDate(date) {
    let separator = "-";
    let year = date.getFullYear();
    let month = date.getMonth() + 1;
    let strDate = date.getDate();
    if (month >= 1 && month <= 9) {
        month = "0" + month;
    }
    if (strDate >= 0 && strDate <= 9) {
        strDate = "0" + strDate;
    }
    return year + separator + month + separator + strDate;
}

export default {
    formatUrl,
    jsonFormat,
    jsonSyntaxHighlight,
    timestampFormat,
    exportExcel,
    isImage,
    isLocalhost,
    toArray,
    convertArray,
    getFormatDate,
}
